package com.chen.websocket;

import cn.hutool.json.JSONUtil;
import com.chen.common.utils.JwtUtil;
import com.chen.judge.codesandbox.model.JudgeResult;
import com.chen.popj.entity.Contest;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Deprecated
//@ServerEndpoint("/contest/{contestId}/{userId}")
public class WebSocketContestServer {
    //存放会话对象
//    private static Map<Integer, Session> sessionMap = new HashMap();
    private static final Map<Object, Session> sessionMap = new ConcurrentHashMap<>();

    @Autowired
    HttpServletRequest httpServletRequest;

    /**
     * 连接建立成功调用的方法
     *
     * @param session
     * @param contestId
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("contestId") Integer contestId
            , @PathParam("userId") Integer userId) {
        System.out.println("WebSocket客户端：" + contestId + "/" + userId + "建立连接");
        sessionMap.put(contestId + "/" + userId, session);
    }


    /**
     * 连接关闭调用的方法
     *
     * @param session
     * @param contestId
     */
    @OnClose
    public void onClose(Session session, @PathParam("contestId") Integer contestId
            , @PathParam("userId") Integer userId) {
        System.out.println("WebSocket客户端" + contestId + "/" + userId + "连接断开");
        sessionMap.remove(contestId + "/" + userId, session);
    }

    /**
     * 使用比赛id和用户id发给指定的客户端
     *
     * @param contestId
     * @param userId
     * @param contest
     */
    public void sendClient(Integer contestId, Integer userId, Contest contest) {
        Session session = sessionMap.get(contestId + "/" + userId);
        try {
            //服务器向客户端发送消息
            String jsonStr = JSONUtil.toJsonStr(contest);
            session.getBasicRemote().sendText(String.valueOf(jsonStr));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
